package servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.Customer;
import service.CustomerManager;
import service.VerifyService;
import service.impl.CustomerManagerFactory;
import service.impl.VerifyListener;
import service.impl.VerifyServiceImpl;

public class AddCustomerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CustomerManager manager;

	public AddCustomerServlet() {
		super();
		// /避免水波效应（降低耦合）
		manager = CustomerManagerFactory.getInstance();
	}

	protected void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException, IOException {
		// /获取 客户端 传来的参数（与前端对接）

		// /接参
		String cname = request.getParameter("cname");
		String csex = request.getParameter("sex");
		String csal = request.getParameter("sal");
		String cbirth = request.getParameter("birth");
		final String[] favs = request.getParameterValues("favs");
		
		if(favs!=null)
		System.out.println("要添加的favs: "+ Arrays.toString(favs));

		// /校验交給Verify做
		VerifyServiceImpl verify = new VerifyServiceImpl();
		verify.setVerifyListener(new VerifyListener() {
			
			@Override
			public void successVerify(Customer customer) {
				// /调用业务 --- 获取返回值
				customer.setFavs(favs);
				int m = manager.addCustomer(customer);
				if (m > 0) {
					// 成功

					// 重定向
					try {
						response.sendRedirect("list");
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					request.setAttribute("msg", "insert error！");
					try {
						request.getRequestDispatcher("/ErrorMsgServlet").forward(request, response);
					} catch (ServletException | IOException e) {
						e.printStackTrace();
					}
				}
			}
			
			@Override
			public void errorDuringVerify(String msg) {
				request.setAttribute("msg", msg);
				try {
					request.getRequestDispatcher("/ErrorMsgServlet").forward(request, response);
				} catch (ServletException | IOException e) {
					e.printStackTrace();
				}
			}
		});
		
		///開始校驗
		  verify.verifyBirth(cbirth);
		  verify.verifySalary(csal);
		  verify.verifyUserName(cname);
		  verify.verifySex(csex);
	}

}
